import * as Router from 'koa-router'
import * as Joi from 'joi'
import { File } from 'formidable'
import * as userService from '../services/user.service'
import { badParams } from '../stats'

const router = new Router({
  prefix: '/api/user'
})

// 登录
router.post('/admin/login', async ctx => {
  const schema = Joi.object({
    username: Joi.string().length(11).required(),
    password: Joi.string().min(6).max(8).required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const tokens = await userService.login(value.username, value.password)
  ctx.set('Set-Cookie', `token=${tokens}; path=/; httpOnly`)
  ctx.body = {
    stat: 'OK',
    tokens
  }
})

// 检验密码
router.post('/front/test', async ctx => {
  const token = ctx.cookies.get('token')
  const schema = Joi.object({
    password: Joi.string().min(6).max(8).required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  await userService.test(token, value.password)
  ctx.body = {
    stat: 'OK'
  }
})

// 注册/登录一起
router.post('/front/loginPlus', async ctx => {
  const schema = Joi.object({
    username: Joi.string().length(11).required(),
    password: Joi.string().min(6).max(8).required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const password = value.password
  const res = await userService.register(value)
  const tokens = await userService.login(value.username, password)
  ctx.set('Set-Cookie', `token=${tokens}; path=/; httpOnly`)
  ctx.body = {
    stat: res,
    tokens
  }
})

// 获取当前登录用户信息
router.post('/front/getInfo', async ctx => {
  const token = ctx.cookies.get('token')
  const userInfo = await userService.userInfo(token)
  ctx.body = {
    stat: 'OK',
    data: userInfo
  }
})

// 根据id获取用户信息
router.post('/front/userInfo', async ctx => {
  const schema = Joi.object({
    id: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const result = await userService.findUserInfo(value.id)
  ctx.body = {
    stat: 'OK',
    data: result
  }
})

// 用户自己更新用户信息
router.post('/front/addInfo', async ctx => {
  const token = ctx.cookies.get('token')
  const result = await userService.userInfo(token)
  if (result) {
    // 已经登录，有token值
    const schema = Joi.object({
      avatar: Joi.string(),
      name: Joi.string().min(2).max(5),
      sex: Joi.number(),
      positionName: Joi.string(),
      password: Joi.string().min(6).max(8)
    })
    const { value, error } = schema.validate(ctx.request.body)
    if (error) throw badParams(error.message)
    await userService.addInfo(token, value)
    ctx.body = {
      stat: 'OK',
      message: '信息已经更改'
    }
  } else {
    ctx.body = {
      stat: 'ERR_NOT_LOGIN',
      message: '用户未登录'
    }
  }
})

// 退出登录
router.post('/logout', ctx => {
  const token = ctx.cookies.get('token')
  userService.logout(token)
  ctx.set(
    'Set-Cookie',
    `token=; path=/; expires=${new Date().toUTCString()}; httpOnly`
  )
  ctx.body = {
    stat: 'OK'
  }
})

// 查看是否收藏
router.post('/fav/find', async ctx => {
  const token = ctx.cookies.get('token')
  const result = await userService.userInfo(token)
  const schema = Joi.object({
    id: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) {
    ctx.body = {
      stat: 'ERR_BAD_PARAMS',
      message: error.message
    }
  }
  const res = await userService.findFav(result._id, value.id)
  if (res) {
    ctx.body = {
      data: true
    }
  } else {
    ctx.body = {
      data: false
    }
  }
})

// 添加收藏
router.post('/fav/add', async ctx => {
  const token = ctx.cookies.get('token')
  const schema = Joi.object({
    IRecruitId: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) {
    ctx.body = {
      stat: 'ERR_BAD_PARAMS',
      message: error.message
    }
  }
  const result = await userService.addFav(token, value.IRecruitId)
  ctx.body = {
    stat: 'OK',
    data: result
  }
})

// 收藏页列表
router.post('/fav/list', async ctx => {
  const token = ctx.cookies.get('token')
  const items = await userService.listFav(token)
  ctx.body = {
    stat: 'OK',
    items
  }
})

// 删除收藏
router.post('/fav/remove', async ctx => {
  const schema = Joi.object({
    id: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) {
    ctx.body = {
      stat: 'ERR_BAD_PARAMS',
      message: error.message
    }
  }
  const result = await userService.removeFav(value.id)
  ctx.body = {
    stat: 'OK',
    result
  }
})

// 头像上传
router.post('/upload', async ctx => {
  const token = ctx.cookies.get('token')
  const file = Object.values(ctx.request.files)[0] as File
  const key = await userService.upload(token, file.path, file.size, file.name)
  ctx.body = {
    stat: 'OK',
    data: key
  }
})

// 获取企业用户列表
router.post('/company/userlist', async ctx => {
  const schema = Joi.object({
    id: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const rows = await userService.userlist(value.id)
  ctx.body = {
    stat: 'OK',
    rows
  }
})

// 获取所有普通用户（除系统管理员外的所有用户）
router.post('/userlist', async ctx => {
  const token = ctx.cookies.get('token')
  const rows = await userService.allUserlist(token)
  ctx.body = {
    stat: 'OK',
    rows
  }
})

// 添加企业用户
router.post('/company/userAdd', async ctx => {
  const schema = Joi.object({
    username: Joi.string().min(6).max(11).required(),
    companyId: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  await userService.userAdd(value.username, value.companyId)
  ctx.body = {
    stat: 'OK'
  }
})

// 删除企业用户
router.post('/user/remove', async ctx => {
  const token = ctx.cookies.get('token')
  const schema = Joi.object({
    id: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const result = await userService.removerCompanyUser(value.id, token)
  ctx.body = {
    stat: 'OK',
    result
  }
})

// 禁用恢复用户
router.post('/status', async ctx => {
  const schema = Joi.object({
    id: Joi.string()
  })
  const { value } = schema.validate(ctx.request.body)
  await userService.userStatus(value.id)
  ctx.body = {
    stat: 'OK'
  }
})

/**
 * 根据key下载文件
 */
router.get('/download/:id', async ctx => {
  const id = ctx.params.id
  const file = await userService.download(id)
  ctx.set('Content-Type', 'application/octet-stream')
  ctx.res.setHeader(
    'Content-Disposition',
    'attachment; filename=' + encodeURIComponent(file.name)
  )
  ctx.body = file.data.buffer
})

// 编辑用户信息
router.put('/edit', async ctx => {
  const token = ctx.cookies.get('token')
  const schema = Joi.object({
    password: Joi.string().min(6).max(8),
    avatar: Joi.string(),
    name: Joi.string().min(2).max(5),
    sex: Joi.number()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  await userService.edit(value, token)
  ctx.body = {
    stat: 'OK'
  }
})

// 高级用户修改用户信息
router.post('/editPlus', async ctx => {
  const token = ctx.cookies.get('token')
  const schema = Joi.object({
    id: Joi.string().required(),
    isDisabled: Joi.number(),
    companyId: Joi.string()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const id = value.id
  delete value.id
  await userService.editPlus(value, token, id)
  ctx.body = {
    stat: 'OK'
  }
})

export default router
